package com.hitqz.robot.biz.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.util.URLUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.cache.Cache;
import com.hitqz.robot.api.business.dto.RobotClientSummaryDto;
import com.hitqz.robot.api.business.dto.VisionDetectSaveDTO;
import com.hitqz.robot.api.business.entity.VisionDetectEntity;
import com.hitqz.robot.api.dispatch.protocol.dto.RobotWarningDto;
import com.hitqz.robot.biz.mapper.VisionDetectMapper;
import com.hitqz.robot.biz.service.VisionDetectService;
import com.hitqz.robot.common.file.core.FileProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import lombok.RequiredArgsConstructor;

import java.io.File;
import java.net.URL;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * 视觉检测记录
 *
 * @author kehanjiang
 * @date 2025-09-23 11:03:39
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class VisionDetectServiceImpl extends ServiceImpl<VisionDetectMapper, VisionDetectEntity> implements VisionDetectService {
    private final FileProperties fileProperties;

    @Override
    public Boolean saveVisionDetect(VisionDetectSaveDTO dto) {
        Assert.isTrue(StringUtils.hasText(dto.getTitle()), "标题不能为空");
        Assert.isTrue(StringUtils.hasText(dto.getContent()), "内容不能为空");
        Assert.isTrue(StringUtils.hasText(dto.getType()), "类型不能为空");
        Assert.isTrue(StringUtils.hasText(dto.getPath()), "原始图片地址不能为空");
        VisionDetectEntity entity = new VisionDetectEntity();
        BeanUtils.copyProperties(dto, entity);
        String path = dto.getPath();
        String extName = FileUtil.extName(path);
        String filePath = fileProperties.getLocal().getBasePath() + File.separator + "vision_detect" + File.separator + DateUtil.format(new Date(), "yyyy-MM-dd") + File.separator + DateUtil.format(new Date(), "HHmmssSSS") + "." + extName;
        String relativePath = normalizePath(filePath).replace(normalizePath(fileProperties.getLocal().getBasePath()), "/sys-file");
        try {
            URL url = URLUtil.url(path);
            FileUtil.writeFromStream(URLUtil.getStream(url), filePath);
            entity.setConvertPath(relativePath);
        } catch (IORuntimeException e) {
            log.error("下载视觉图片失败,{}", e.getMessage());
        }
        Cache<String, RobotClientSummaryDto> posInfoDtoCache = SpringUtil.getBean("robotCache");
        Iterable<String> cacheKeys = posInfoDtoCache.asMap().keySet();
        String firstKey = cacheKeys.iterator().hasNext() ? cacheKeys.iterator().next() : null;
        RobotClientSummaryDto robotClientSummaryDto = firstKey != null ? posInfoDtoCache.getIfPresent(firstKey) : null;
        if (robotClientSummaryDto != null) {
            String posCode = robotClientSummaryDto.getPosition().getLaserPos().getNearPosCode();
            entity.setPosCode(posCode);
        }
        boolean b = save(entity);
        if (b) {
            String robotName = robotClientSummaryDto.getStatus().getName();
            String robotSn = robotClientSummaryDto.getStatus().getSn();
            //插入告警
            RobotWarningDto warningDto = new RobotWarningDto();
            warningDto.setContent(entity.getContent());
            warningDto.setRobotSn(robotSn);
            warningDto.setWarningObj("定时检测:"+entity.getType());
            warningDto.setLevel(1);
            SpringUtil.getApplicationContext().publishEvent(warningDto);
        }
        return Boolean.TRUE;
    }


    // 工具方法：将路径统一转为 "/" 分隔
    private String normalizePath(String path) {
        return path.replace("\\", "/");
    }
}